/*
 * @FileName: app_calibration.c
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-08-21 10:50:15
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-27 09:13:43
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */
#include "app_calibration.h"
#include "app_fault.h"
#include "app_analog.h"
#include "bsp_flash.h"
#include "log.h"
uint16_t coff_save_flag = 0;

calibration_t factor[FACTOR_IDX_NUM];

flash_obj_t app_data;

void app_calib_init(void)
{
    bsp_flash_obj_init(&app_data, DEVICE_DATA_ADDR, DEVICE_DATA_SIZE);
    bsp_flash_read(&app_data, 0, (uint8_t *)factor, sizeof(calibration_t) * FACTOR_IDX_NUM);

    // 检查校准参数是否合法
    uint16_t reset_flag = 0;
    uint16_t save_flag = 0;
    uint16_t i;
    for (i = 0; i < FACTOR_IDX_NUM; i++) {
        reset_flag = 0;
        if (factor[i].k > FACTOR_K_MAX || factor[i].k < FACTOR_K_MIN) {
            reset_flag = 1;
        }

        if (factor[i].b > FACTOR_B_MAX || factor[i].b < FACTOR_B_MIN) {
            reset_flag = 1;
        }

        if (reset_flag == 1)
        {
            factor[i].k = FACTOR_K_DEFAULT;
            factor[i].b = FACTOR_B_DEFAULT;
            save_flag = 1; 
        }
        log_debug("%d k = %d, b = %d\n", i, factor[i].k, factor[i].b);
    }

    if (save_flag == 1) {
        bsp_flash_page_erase(&app_data, 0, 1); // 擦除
        bsp_flash_write(&app_data, 0, (uint8_t *)factor, sizeof(calibration_t) * FACTOR_IDX_NUM); // 写入
    }

    // 初始化各采样校准系数
    for (i = 0; i < FACTOR_IDX_NUM; i++) {
        analog_tbl[i].k1 =  0.0001f * factor[i].k;
        analog_tbl[i].b1 =  0.0001f * factor[i].b;
    }
}


uint16_t app_calib_config(uint8_t id, uint16_t k, int16_t b)
{
    log_debug("%d app_calib_config k = %d b = %d\n", id, k, b);
    if (id >= FACTOR_IDX_NUM) {
        return 0;
    }

    if (k > FACTOR_K_MAX || k < FACTOR_K_MIN) {
        return 0;
    }

    if (b > FACTOR_B_MAX || b < FACTOR_B_MIN) {
        return 0;
    }

    factor[id].k = k;
    factor[id].b = b;

    analog_tbl[id].k1 =  0.0001f * factor[id].k;
    analog_tbl[id].b1 =  0.0001f * factor[id].b;

    // if (id == FACTOR_IDX_IOUT) {
        bsp_flash_page_erase(&app_data, 0, 1); // 擦除
        bsp_flash_write(&app_data, 0, (uint8_t *)factor, sizeof(calibration_t) * FACTOR_IDX_NUM); // 写入
    // }

    return 1;
}
